/*

Morpheme
Copyright (C) 2012 Francisco Monteiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

http://code.google.com/p/morpheme-tumblr-theme/

*/

var Morpheme = {
    config: { // Default Configurations

        // NON optional configs
        url: null,
        morphemeExtensionEvents: null,

        // optional configs
        startPage: 0,
        postsPerLoad: 16, // this should match the posts per page you've configured for your tumblr (only if you're running this as a tumblr theme)
        postType: null,
        timeout: 10000
    },

    state: {
        firstShow: true,
        isRunning: false,
        finished: false,
        json: null,

        // "initialized":
        currentPage: 0,
        blogUrl: null,
        postId: null,
        tag: null,
        isSafeToLoad: null
    },

    initialize: function(configs) {
        'use strict';

        $.extend(Morpheme.config, configs);

        Morpheme.state.blogUrl = Morpheme.utils.url.getBlogUrl(Morpheme.config.url);
        Morpheme.state.postId = Morpheme.utils.url.getPostId(Morpheme.config.url);
        Morpheme.state.tag = Morpheme.utils.url.getTag(Morpheme.config.url);

        Morpheme.state.currentPage = (Morpheme.state.tag || Morpheme.state.postId) ? 0: Morpheme.config.startPage;

        Morpheme.state.isSafeToLoad = Morpheme.utils.isSafeToLoad();
        
        if (Morpheme.config.morphemeExtensionEvents && Morpheme.config.morphemeExtensionEvents.initialize) {
            Morpheme.config.morphemeExtensionEvents.initialize();
        }
    },

    loadPosts: function() {
        'use strict';

        if (
            Morpheme.state.isRunning || 
            !Morpheme.state.isSafeToLoad ||
            Morpheme.state.finished
        ) {
            return false;
        }

        Morpheme.state.isRunning = true;

        if (Morpheme.state.postId) { // ________________________________ post by id
            Morpheme.state.json = Morpheme.utils.tumblrAPI.load.Post(
                Morpheme.loadPostsFinishedEvent,
                Morpheme.config.timeout, 

                Morpheme.state.blogUrl,
                Morpheme.state.postId
            );
        } else {
            if (Morpheme.state.tag) { // _______________________________ posts by tag
                Morpheme.state.json = Morpheme.utils.tumblrAPI.load.taggedPosts(
                    Morpheme.loadPostsFinishedEvent,
                    Morpheme.config.timeout, 

                    Morpheme.state.blogUrl,
                    Morpheme.state.tag
                );
            } else { // ________________________________________________ posts by page
                Morpheme.state.json = Morpheme.utils.tumblrAPI.load.Posts(
                    Morpheme.loadPostsFinishedEvent,
                    Morpheme.config.timeout, 

                    Morpheme.state.blogUrl,
                    Morpheme.state.currentPage * Morpheme.config.postsPerLoad, 
                    Morpheme.config.postsPerLoad, 
                    Morpheme.config.postType
                );
            }
        }

        return true;
    },


    loadPostsFinishedEvent: function(error) {
        'use strict';

        if (error === 0) { // ______________ no error
            Morpheme.loadPostsFinished();
        } else { // ________________________ some error
            if (Morpheme.config.morphemeExtensionEvents && Morpheme.config.morphemeExtensionEvents.postsError) {
                Morpheme.config.morphemeExtensionEvents.postsError(error);
            }

            Morpheme.state.isRunning = false;
        }

        return;
    },

    loadPostsFinished: function() {
        'use strict';

        if (Morpheme.state.firstShow) {
            Morpheme.state.firstShow = false;

            if (Morpheme.config.morphemeExtensionEvents && Morpheme.config.morphemeExtensionEvents.headReady) {
                Morpheme.config.morphemeExtensionEvents.headReady();
            }
        }

        Morpheme.state.currentPage++;

        if (
            Morpheme.state.postId ||
            Morpheme.state.tag ||
            ((Morpheme.state.currentPage * Morpheme.config.postsPerLoad) > Number(tumblr_api_read['posts-total']))
        ) {
            Morpheme.state.finished = true;
        }

        if (Morpheme.config.morphemeExtensionEvents && Morpheme.config.morphemeExtensionEvents.postsReady) {
            Morpheme.config.morphemeExtensionEvents.postsReady(Morpheme.state.finished);
        }
        if (Morpheme.state.finished && Morpheme.config.morphemeExtensionEvents && Morpheme.config.morphemeExtensionEvents.noMorePosts) {
            Morpheme.config.morphemeExtensionEvents.noMorePosts();
        }

        Morpheme.state.isRunning = false;
    },


    utils: {
        script: {
            load: function(finishedEvent, timeout, url) {
                'use strict';

                var
                    to = setTimeout(
                        function() {
                            to = null;
                            if (finishedEvent) {
                                finishedEvent(1);
                            }
                        }, 
                        timeout
                    ),
                    doc = document,
                    scriptElement = doc.createElement('script'),
                    script = doc.getElementsByTagName('script')[0];

                scriptElement.type = 'text\/javascript';
                scriptElement.async = true;
                script.parentNode.insertBefore(scriptElement, script);

                //$.getScript(
                //    url, 
                //    function (data, textStatus) {
                //        if (to) {
                //            clearTimeout(to);
                //            to = null;
                //            if (finishedEvent) {
                //                finishedEvent((textStatus === 'success') ? 0 : 2);
                //            }
                //        }
                //    }
                //);

                scriptElement.onload = function() {
                    if (to) {
                        clearTimeout(to);
                        to = null;

                        if (finishedEvent) {
                            finishedEvent(0);
                        }
                    }
                };
                scriptElement.src = url;
            }
        },

        image: {
            load: function(imageElement, src, successEvent, timeout, timeoutEvent) {
                'use strict';

                var to = setTimeout(
                    function() {
                        to = null;
                        if (timeoutEvent) {
                            timeoutEvent();
                        }
                    },
                    timeout
                );

                imageElement.onload = function() {
                    if (to) {
                        clearTimeout(to);
                        to = null;

                        if (successEvent) {
                            successEvent();
                        }
                    }
                };
                imageElement.src = src;

                // making it possible to cancel timeout event, in case it's needed
                return to;
            }
        },

        stripper: {
            htmlstripper__: null,
            stripHTML: function (html) {
                'use strict';

                if (!html) { return ''; }

                if (!this.htmlstripper__) { this.htmlstripper__ = document.createElement('DIV'); }

                this.htmlstripper__.innerHTML = html;

                //return (this.htmlstripper__.innerText || this.htmlstripper__.textContent);

                var
                    yyy,
                    xxx = (this.htmlstripper__.innerText || this.htmlstripper__.textContent);
                this.htmlstripper__.innerHTML = xxx;
                yyy = (this.htmlstripper__.innerText || this.htmlstripper__.textContent);
                if (xxx !== yyy) {
                    return this.stripHTML(yyy);
                } else {
                    return xxx;
                }
            },

            scriptstripperevents__: 'load|unload|blur|change|focus|reset|select|submit|abort|keydown|keypress|keyup|click|dblclick|mousedown|mousemove|mouseout|mouseover|mouseup'.split('|'),
            scriptstripper__: null,
            stripScripts: function (script) {
                'use strict';

                if (!this.scriptstripper__) { this.scriptstripper__ = document.createElement('DIV'); }

                this.scriptstripper__.innerHTML = script;

                var
                    scripts,
                    index,
                    objects = this.scriptstripper__.getElementsByTagName('object');
                index = objects.length;
                while (index--) { objects[index].parentNode.removeChild(objects[index]); }

                scripts = this.scriptstripper__.getElementsByTagName('script');
                index = scripts.length;
                while (index--) { scripts[index].parentNode.removeChild(scripts[index]); }

                for (
                    var
                        allElements = this.scriptstripper__.getElementsByTagName('*'),
                        j = 0;
                    j < allElements.length;
                    j++
                ) {
                    for (var i = 0; i < this.scriptstripperevents__.length; i++) {
                        if (allElements[j].hasAttribute('on' + this.scriptstripperevents__[i])) {
                            allElements[j].removeAttribute('on' + this.scriptstripperevents__[i]);
                        }
                    }
                }

                return this.scriptstripper__.innerHTML;
            },

            anchorstripper__: null,
            stripAnchors: function (script) {
                'use strict';

                if (!this.anchorstripper__) { this.anchorstripper__ = document.createElement('DIV'); }

                this.anchorstripper__.innerHTML = script;

                var 
                    anchors = this.anchorstripper__.getElementsByTagName('a'),
                    j = anchors.length;
                while (j--) {
                    //anchors[j].removeAttribute('title');
                    //anchors[j].href = '';

                    //$(anchors[j]).click(function (e) {
                    //    e.preventDefault();
                    //});
                    anchors[j].setAttribute('onclick', 'return false;');
                }

                return this.anchorstripper__.innerHTML;
            }

        },

        url: {
            blogurl__: null,
            getBlogUrl: function(fullUrl) {
                'use strict';

                if (!this.blogurl__) {

                    // ToDos: here!
                    //
                    // it looks bad and it only works for: 
                    // - http://SomeTumblr.tumblr.com/whatever
                    // - SomeTumblr
                    // should also work for:
                    // - SomeTumblr.tumblr.com/whatever
                    //
                    // now working but still looks bad
                    //

                    var
                        j,
                        i = fullUrl.toLowerCase().indexOf('http:\/\/');
                    if (i >= 0) {
                        if ( 
                            ((j = fullUrl.indexOf('\/', i + 7)) >= 0) ||
                            ((j = fullUrl.indexOf('?', i + 7)) >= 0)
                        ) {
                            this.blogurl__ = fullUrl.substring(i, j);
                        } else {
                            this.blogurl__ = fullUrl.substring(i);
                        }
                    } else {
                        j = fullUrl.indexOf('.');
                        if (j >= 0) {
                            this.blogurl__ = this.getBlogUrl('http:\/\/' + fullUrl);
                        } else {
                            this.blogurl__ = 'http:\/\/' + fullUrl + '.tumblr.com';
                        }
                    }
                }
                return this.blogurl__;
            },

            postid__: null,
            getPostId: function(fullUrl) {
                'use strict';

                if (!this.postid__) {
                    var
                        j,
                        i = fullUrl.toLowerCase().lastIndexOf('\/post\/');
                    if ((i > 0) && (fullUrl.length !== i + 6)) {
                        j = fullUrl.substring(i + 6);

                        if (
                            ((i = j.indexOf('\/')) > 0) ||
                            ((i = j.indexOf('?')) > 0)
                        ) {
                            j = j.substring(0, i);
                        }

                        this.postid__ = j;
                    } else {
                        this.postid__ = null;
                    }
                }

                return this.postid__;
            },

            tag__: null,
            getTag: function(fullUrl) {
                'use strict';

                if (!this.tag__) {
                    var
                        j,
                        i = fullUrl.toLowerCase().lastIndexOf('\/tagged\/');
                    if ((i > 0) && (fullUrl.length !== i + 8)) {
                        j = fullUrl.substring(i + 8);

                        if (
                            ((i = j.indexOf('\/')) > 0) ||
                            ((i = j.indexOf('?')) > 0)
                        ) {
                            j = j.substring(0, i);
                        }

                        this.tag__ = j;
                    } else {
                        this.tag__ = null;
                    }
                }
                return this.tag__;
            },

//            page__: null,
//            getPage: function(fullUrl) {
//                'use strict';
//
//                if (!this.page__) {
//// ToDos: here!
//                }
//                return this.page__;
//            },

            getParam: {
                urlParamList__: null,

                fullList: function () {
                    'use strict';

                    if (!this.urlParamList__) {
                        var 
                            hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'),
                            hash;
                        this.urlParamList__ = [];
                        for (var i = 0; i < hashes.length; i++) {
                            hash = hashes[i].split('=');
                            this.urlParamList__.push(hash[0]);
                            this.urlParamList__[hash[0]] = hash[1];
                        }
                    }

                    return this.urlParamList__;
                },
                byName: function (name) {
                    'use strict';

                    return (this.urlParamList__
                        ? this.urlParamList__[name]
                        : this.fullList()[name]
                    );
                }
            }
        },

        tumblrAPIv2: {
            API_URL: 'http:\/\/api.tumblr.com\/v2',

            config: {
                key: null,
                url: null
            },

            initialize: function(configs) {
                'use strict';

                $.extend(this.config, configs);
            },

            read: {
                info: null,
                posts: null
            },
            saveCall: {
                info: function(answer) {
                    'use strict';

                    Morpheme.utils.tumblrAPIv2.read.info = answer;
                },
                posts: function(answer) {
                    'use strict';

                    Morpheme.utils.tumblrAPIv2.read.posts = answer;
                }
            },

            load: {
                info: function(finishedEvent, timeout) {
                    'use strict';

                    var url =
                        Morpheme.utils.tumblrAPIv2.API_URL +
                        '\/blog\/' +
                        Morpheme.utils.tumblrAPIv2.config.url +
                        '\/info?api_key=' +
                        Morpheme.utils.tumblrAPIv2.config.key +
                        '&jsonp=Morpheme.utils.tumblrAPIv2.saveCall.info'
                    ;

                    Morpheme.utils.tumblrAPIv2.read.info = null;
                    Morpheme.utils.script.load(
                        function(error) {
                            if (!Morpheme.utils.tumblrAPIv2.read.info) {
                                finishedEvent(2);
                            } else if (Morpheme.utils.tumblrAPIv2.read.info.meta.status !== 200) {
                                Morpheme.utils.tumblrAPIv2.read.info = null;
                                finishedEvent(Morpheme.utils.tumblrAPIv2.read.info.meta.status);
                            } else {
                                finishedEvent(error);
                            }
                        },
                        timeout,
                        url
                    );
                    return url;
                },
                posts: function(finishedEvent, timeout, type, id, tag, limit, offset, format) {
                    'use strict';

                    //limit: [1, 20]
                    //reblog_info: true, false
                    //notes_info: true, false
                    //format: text, raw

                    var url =
                        Morpheme.utils.tumblrAPIv2.API_URL +
                        '\/blog\/' +
                        Morpheme.utils.tumblrAPIv2.config.url +
                        '\/posts' +
                        (type
                            ? ('\/' + type)
                            : ''
                        ) +
                        '?api_key=' +  Morpheme.utils.tumblrAPIv2.config.key +
                        '&reblog_info=false' +
                        '&notes_info=false' +
                        (id
                            ? '&id=' + id
                            : ''
                        ) +
                        (tag
                            ? ('&tag=' + tag)
                            : ''
                        ) +
                        (limit
                            ? ('&limit=' + limit)
                            : ''
                        ) +
                        (offset
                            ? ('&offset=' + offset)
                            : ''
                        ) +
                        (format
                            ? ('&format=' + format)
                            : ''
                        ) +
                        '&jsonp=Morpheme.utils.tumblrAPIv2.saveCall.posts'
                    ;

                    Morpheme.utils.tumblrAPIv2.read.posts = null;
                    Morpheme.utils.script.load(
                        function(error) {
                            //'use strict';//Unnecessary directive "use strict".

                            if (!Morpheme.utils.tumblrAPIv2.read.posts) {
                                finishedEvent(2);
                            } else if (Morpheme.utils.tumblrAPIv2.read.posts.meta.status !== 200) {
                                finishedEvent(Morpheme.utils.tumblrAPIv2.read.posts.meta.status);
                                Morpheme.utils.tumblrAPIv2.read.posts = null;
                            } else {
                                finishedEvent(error);
                            }
                        },
                        timeout,
                        url
                    );
                    return url;
                }
            }
        },

        tumblrAPI: {
            load: {
                Post: function(finishedEvent, timeout, url, id) {
                    'use strict';

                    var output = Morpheme.utils.tumblrAPI.getJsonUrl.posts(url, id, null, null, null, null);
                    Morpheme.utils.script.load(finishedEvent, timeout, output);
                    return output;
                },
                Posts: function(finishedEvent, timeout, url, start, num, type) {
                    'use strict';

                    var output = Morpheme.utils.tumblrAPI.getJsonUrl.posts(url, null, null, start, num, type);
                    Morpheme.utils.script.load(finishedEvent, timeout, output);
                    return output;
                },
                taggedPosts: function(finishedEvent, timeout, url, tagged) {
                    'use strict';

                    var output = Morpheme.utils.tumblrAPI.getJsonUrl.posts(url, null, tagged, null, null, null);
                    Morpheme.utils.script.load(finishedEvent, timeout, output);
                    return output;
                }
            },

            likeIFrame: function(index, url) {
                'use strict';

                return 'https:\/\/www.tumblr.com\/dashboard\/iframe?' +
                    'src=' + encodeURIComponent(url) + '%2Fpost%2F' + tumblr_api_read.posts[index].id + 
                    'url=' + encodeURIComponent(url) +
                    '&amp;pid=' + tumblr_api_read.posts[index].id + 
                    '&amp;rk=' + tumblr_api_read.posts[index]['reblog-key'] + 
                    '&amp;name=' + tumblr_api_read.tumblelog.name +
                    '&amp;page_slide=slide&amp;lang=en_US&amp;_v=99c0fb41c8468e713a057ca6c55f1bc0'
                ;
            }, 

            avatar: function(name, size) {
                'use strict';

                var 
                    name2 = (name ? name : tumblr_api_read.tumblelog.name),
                    size2;
                switch (size) {
                    case 0:    size2 =  16; break;
                    case 1:    size2 =  24; break;
                    case 2:    size2 =  30; break;
                    case 3:    size2 =  40; break;
                    case 4:    size2 =  48; break;
                    case 5:    size2 =  64; break;
                    case 6:    size2 =  96; break;
                    case 7:    size2 = 128; break;
                    case 8:    size2 = 512; break;

                    default:   size2 =  96; break;
                }

                return Morpheme.utils.tumblrAPIv2.API_URL + '\/blog\/' + name2 + '.tumblr.com\/avatar\/' + size2;
            },

            getJsonUrl: {
                forPost: function(url, id) {
                    'use strict';

                    return this.posts(url, id, null, null, null, null);
                }, 
                forPosts: function(url, start, num, type) {
                    'use strict';

                    return this.posts(url, null, null, start, num, type);
                },
                forTaggedPosts: function(url, tagged) {
                    'use strict';

                    return this.posts(url, null, tagged, null, null, null);
                }, 

                posts: function(url, id, tagged, start, num, type) {
                    'use strict';

                    var output = url + '\/api\/read\/json?noCache='+(new Date().getTime())+'&';

                    if (id && (id > 0)) {
                        output += 'id=' + id;
                    }

                    else if (tagged) {

                        // note: tagged parameter incompatible with start parameter, bad for paging,
                        //
                        // doesn't work:
                        // http://acarro.tumblr.com/api/read/json?num=10&tagged=acarro&start=1
                        //
                        // this one does: (maximum is 50)
                        // http://acarro.tumblr.com/api/read/json?num=50&tagged=acarro

                        output += 
                            'num=50' +
                            '&tagged=' + tagged.replace(/_/gi, ' ').replace(/\+/gi, ' ');
                    }

                    else {
                        output +=
                            'start=' + start +
                            '&num=' + num +
                            (
                                type ? ('&type=' + type) : ''
                            );
                    }

                    return output;
                }
            }
        },



        windowLocationHrefNoParams: function () {
            'use strict';

            var q = window.location.href.indexOf('?');
            return (q >= 0) ? window.location.href.substring(0, q) : window.location.href;
        },

        issafetoload__: null,
        isSafeToLoad: function() {
            'use strict';

            if (!this.issafetoload__) {

                var 
                    ASKLINK = '\/ask',
                    j = window.location.href.toLowerCase();

                this.issafetoload__ = (

                    // !previewing post
                    (j.indexOf('tumblr.com\/reblog\/') < 0) &&
                    (j.indexOf('tumblr.com\/edit\/') < 0) &&
                    (j.indexOf('tumblr.com\/private\/') < 0) &&

                    // !theme customize
                    // note:
                    // - main tumblr customization: tumblr.com\/customize
                    // - other tumblrs customization: tumblr.com\/customize\/SomeOtherSubTumblr
                    (j.indexOf('tumblr.com\/customize') < 0) &&

                    // !theme installer
                    (j.indexOf('safe.tumblr.com\/theme\/preview\/') < 0) &&

                    // !ask
                    !(
                        window.location.pathname &&
                        (window.location.pathname.length >= ASKLINK.length) &&
                        ((window.location.pathname.toLowerCase().lastIndexOf(ASKLINK) + ASKLINK.length + 1) >= window.location.pathname.length)
                    )

                );
            }
            return this.issafetoload__;
        }
    }
};